# coding: utf-8
# @Author: 莫小鱼

import logging
import os
import time
import colorlog
from logging.handlers import RotatingFileHandler  # 按文件大小滚动备份

from AutoWebTest.config import setting


log_path = setting.FILE_PATH['log']

# 从config.setting文件中读取log日志存放路径
if not os.path.isdir(log_path):
    os.mkdir(log_path)

# 日志名字
logfile_name = log_path + r"\test.{}.log".format(time.strftime("%Y%m%d"))


class RecordLog:

    def __init__(self):
        pass

    @classmethod
    def log_color(cls):
        log_color_config = {
            'DEBUG': 'cyan',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'red'
        }
        formater = colorlog.ColoredFormatter(
            '%(log_color)s %(levelname)s - %(asctime)s - %(filename)s:%(lineno)d - [%(module)s:%(funcName)s] - %(message)s ',
            log_colors=log_color_config)

        return formater

    def output_logging(self):
        # 绑定句柄到logger对象
        logger = logging.getLogger(__name__)
        stream_format = self.log_color()
        # 防止重复打印日志
        if not logger.handlers:
            # 设置日志输出级别
            logger.setLevel(level=logging.DEBUG)
            # 设置日志的格式
            # date_string = '%Y-%m-%d %H:%M:%S'
            formatter = logging.Formatter(
                '%(levelname)s - %(asctime)s - %(filename)s:%(lineno)d - [%(module)s:%(funcName)s] - %(message)s ')
            # 把log日志信息输出到控制台
            sh = logging.StreamHandler()
            sh.setLevel(logging.DEBUG)
            sh.setFormatter(stream_format)
            logger.addHandler(sh)

            # 把log日志信息输出到指定文件中
            fh = RotatingFileHandler(filename=logfile_name, mode='a', maxBytes=5242880, backupCount=7, encoding='utf-8')
            fh.setLevel(logging.DEBUG)
            fh.setFormatter(formatter)
            logger.addHandler(fh)

        return logger


# 调用时使用logs
rec = RecordLog()
logs = rec.output_logging()

"""
logs.info("这是info信息")
logs.debug("这是debug信息")
logs.error("这是错误信息")
logs.warning("这是警告信息")
logs.critical("这是紧急信息")

# 获取当前工具文件所在路径
root_path = os.path.dirname(os.path.abspath(__file__))

# 创建日志记录器
file_log_handler = RotatingFileHandler(os.sep.join([log_path, 'log.log']), maxBytes=1024 * 1024, backupCount=10,
                                       encoding="utf-8")
# 设置日志的格式
date_string = '%Y-%m-%d %H:%M:%S'
# formatter = logging.Formatter(
#     '[%(asctime)s] [%(levelname)s] [%(filename)s]/[line: %(lineno)d]/[%(funcName)s] %(message)s ', date_string)
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s (%(filename)s:%(lineno)s)', date_string)
# 日志输出到控制台的句柄
stream_handler = logging.StreamHandler()
# 将日志记录器指定日志的格式
file_log_handler.setFormatter(formatter)
stream_handler.setFormatter(formatter)
# 为全局的日志工具对象添加日志记录器
# 绑定句柄到logger对象
logger.addHandler(stream_handler)
logger.addHandler(file_log_handler)
"""
